import { TextEncoder } from "util";
import networkutil from "../utils/network"
import {enc} from 'crypto-js';
import {saveAs} from 'file-saver';
import { UserHelper } from "../helper";

const uploadFile = (file:File,serverDir:string)=> {
    console.debug("got file to be uploaded, and file size is "+file.size);
   return uploadFileWithProgress(file,serverDir,null);
    // return new Promise((resolve,reject)=>{
    //     var fr = new FileReader();
    //     fr.onload = ()=> {
    //         var imageTxt = fr.result;
    //         if(typeof imageTxt === 'string'){
    //          let wordarray = enc.Utf8.parse(imageTxt);
    //          let base64Str = enc.Base64.stringify(wordarray); 
    //          networkutil.post("/files/upload",{params:{
    //             content:base64Str,name:file.name,
    //             dir:serverDir,type:file.type,size:file.size}})
    //             .then((resp)=>{
    //                 resolve(resp);
    //             }).catch((err)=>{
    //                 reject(err)
    //             });
    //         }
    //      }   
    //      fr.onerror = (err)=> {
    //         reject(err);
    //      }  
    //      fr.readAsBinaryString(file)    
    // })
}

const uploadFileWithProgress = (file:File,serverDir:string,onProgress:any)=> {
    console.debug("got file to be uploaded, and file size is "+file.size);
    return new Promise((resolve,reject)=>{
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress",(e)=>{
            const progress = e.loaded/e.total;
            if(progress < 1){
             onProgress && onProgress(progress);
            }
        })
        xhr.addEventListener("load",(res)=>{
            const respText =  xhr.responseText||"{}";
            console.debug("got response after uploading: "+respText);
            resolve(JSON.parse(respText));
        })

        xhr.upload.addEventListener("error",(err)=>{
           reject(err);
        })

        xhr.open("POST","/api/files/upload",true);

        var userInfo = UserHelper.getCachedUserInfo();
        console.info("got user info from cache: "+JSON.stringify(userInfo));     
        // xhr.setRequestHeader("Content-Type","multipart/form-data");
        xhr.setRequestHeader("Accept","application/json");
        xhr.setRequestHeader("authorization",userInfo.token || "");

        var params = new FormData();
        params.append("afile",file);
        params.append("dir",serverDir);
        params.append("name",file.name);
        params.append("type",file.type);
        params.append("size",file.size.toString());
        xhr.send(params);
        
    })
}

const downloadFile = (url?:string,filename?:any,request?:{headers?:any,queries?:any,params?:any})=>{
    if(!url || !filename){
        return Promise.reject("url can not be null");
    }
    var userInfo = UserHelper.getCachedUserInfo();
    const defaultHeaders = {
        'authorization':userInfo.token || "",

    };
    return fetch(url,{
        headers:defaultHeaders
    }).then((res)=>{
        return res.blob();
    }).then((data)=>{
        return new Promise((resolve,reject)=>{
            saveAs(data,filename)
            resolve(1);
        })
    })
}


export default {
    uploadFile,
    uploadFileWithProgress,
    downloadFile
}